import React, { useState, useEffect } from 'react';
import {
    View, Text, TextInput, ScrollView,
    Image, TouchableOpacity,
} from 'react-native';
import { launchImageLibrary } from 'react-native-image-picker';
import {
    WingBlank, WhiteSpace, Modal, Button, Toast,
} from '@ant-design/react-native';
import PropTypes from 'prop-types';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Tag from '../Tag';
import styles from './styles';
import { createNoteBook, noteBookDetail, editNoteBook } from '../../../../comconfig/sqlfun';

const options = {
    mediaType: 'photo',
    cameraType: 'back',
    saveToPhotos: true,
};
const AddNoteBook = ({ navigation, route }) => {
    const [name, setName] = useState('无标题的笔记本');
    const [show, setShow] = useState(false);
    const [showTag, setShowTag] = useState(false);
    const [imguri, setImgUri] = useState('');
    const [tag, setTag] = useState('');
    const [tags, setTags] = useState([]);
    const [detail, setDetail] = useState({});
    const { getList } = route.params;
    const addImage = async () => {
        const resFromLib = await launchImageLibrary(options);
        const { uri } = resFromLib.assets[0];
        setImgUri(uri);
    };
    const delTag = (index) => {
        const copyTags = [...tags];
        copyTags.splice(index, 1);
        setTags(copyTags);
    };
    const { isEditing, bookid } = route.params;
    const getDetail = async () => {
        try {
            const obj = await noteBookDetail(parseInt(bookid, 10));
            setDetail(JSON.parse(obj));
        } catch (error) {
            Toast.info('获取数据失败', 1, undefined, false);
        }
    };
    useEffect(async () => {
        if (isEditing) {
            getDetail();
        }
    }, []);
    useEffect(() => {
        if (JSON.stringify(detail) !== '{}') {
            setTags(JSON.parse(detail.tag));
            setName(detail.name);
            setImgUri(detail.coveruri);
        }
    }, [detail]);
    navigation.setOptions({
        headerRight: () => (
            <TouchableOpacity
                onPress={async () => {
                    if (!isEditing) {
                        await createNoteBook(name, imguri, tags);
                        getList();
                        navigation.goBack();
                    } else {
                        editNoteBook(parseInt(bookid, 10), name, imguri, tags);
                        getList();
                        navigation.goBack();
                    }
                }}
            >
                <AntDesign
                    name="form"
                    size={26}
                    color="#017BFF"
                    style={{ marginRight: 5 }}
                />
            </TouchableOpacity>
        ),
    });
    return (
        <View>
            <ScrollView>
                <WingBlank>
                    <WhiteSpace />
                    <Text style={styles.describe}>笔记本名字</Text>
                    <WhiteSpace />
                    <TextInput
                        style={styles.name}
                        onChangeText={text => setName(text)}
                        value={name}
                    />
                    <WhiteSpace />
                    <TouchableOpacity
                        onPress={() => { setShow(true); }}
                    >
                        <Text style={styles.describe}>选择封面</Text>
                    </TouchableOpacity>
                    {
                        imguri !== '' && (
                            <View>
                                <WhiteSpace />
                                <Image
                                // resizeMode="repeat"
                                    resizeMethod="scale"
                                    style={styles.iamge}
                                    source={{ uri: imguri }}
                                    defaultSource={require('../../../../assets/images/cover2.jpeg')}
                                />
                            </View>
                        )}
                    <WhiteSpace />
                    <TouchableOpacity
                        onPress={() => setShowTag(true)}
                    >
                        <Text style={styles.describe}>添加标签</Text>
                    </TouchableOpacity>
                    <WhiteSpace />
                    <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
                        {
                            tags.map((item, i) => (
                                <Tag
                                    text={item}
                                    editable
                                    index={i}
                                    delTag={delTag}
                                    key={Math.random() * 100}
                                />
                            ))
                        }
                    </View>
                </WingBlank>
            </ScrollView>
            <Modal
                popup
                visible={show}
                animationType="slide-up"
                maskClosable
                onClose={() => setShow(false)}
            >
                <Button
                    style={{ borderWidth: 0 }}
                    onPress={() => { addImage('library'); setShow(false); }}
                >
                    从相册选择
                </Button>
                <Button
                    style={{ borderWidth: 0 }}
                    onPress={() => setShow(false)}
                >
                    取消
                </Button>
            </Modal>
            <Modal
                title="添加标签 "
                transparent
                onClose={() => { setShowTag(false); setTag(''); }}
                maskClosable
                visible={showTag}
                footer={[
                    {
                        text: '取消',
                        onPress: () => {
                            setShowTag(false);
                            setTag('');
                        },

                    },
                    {
                        text: '确定',
                        onPress: () => {
                            setTags([...tags, tag]);
                            setTag('');
                        },
                    },
                ]}
            >
                <TextInput
                    onChangeText={text => setTag(text)}
                    value={tag}
                />
            </Modal>
        </View>
    );
};
AddNoteBook.defaultProps = {
    route: {},
};
AddNoteBook.propTypes = {
    route: PropTypes.objectOf(PropTypes.any),

};
export default AddNoteBook;
